const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')






// 引入身份验证路由
const auth = require('./routes/auth')

const {sequelize} = require('./config/db')
const cors = require('@koa/cors');

app.use(cors());

// 错误处理
onerror(app)



// 中间件
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// 日志记录
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// 路由

app.use(auth.routes(), auth.allowedMethods())

// 错误处理
app.on('error', (err, ctx) => {
  console.error('服务器错误', err, ctx)
});

// 进行数据库连接验证
sequelize.authenticate().then(()=>{
  console.log('连接成功');
}).catch(err=>{
  console.error('连接失败');
})

module.exports = app